<template>
  <n-scrollbar style="max-height: calc(100vh - 180px);" trigger="none" x-placement="top">
  <div class="schedule-container">
    <!-- 时间刻度列 -->
    <div class="time_big">

    <div class="time-column">
      <div style="width: 5px;position: absolute;left: 55px;z-index: 9;height: 100%;">
        <div v-for="i in 30" :style="{ 'top': `${(i * 30)}px` }" style="position:absolute;width: 100%;height: 1px;background: #8945c3;"></div>
      </div>
      <div
        v-for="hour in hours"
        :key="hour"
        class="time-mark"
        :style="{ top: `${(hour - startHour) * hourHeight}px` }"
      >
        {{ formatHour(hour) }}
      </div>
    </div>
    </div>

    <!-- 客户预约列容器 -->
    <div class="customers-container" ref="customersContainer">
      <!-- 每个客户一列 -->
      <div
        v-for="customer in customers"
        :key="customer.id"
        class="customer-column"
        :style="{ width: `${columnWidth}px` }"
      >
        <div class="customer-header" style="display: flex;align-items: center;text-align: center;justify-content: center">
          <img style="width: 25px;height:25px;border-radius: 50%;margin-right: 5px" v-if="customer.avatar" :src="customer.avatar">
          <img style="width: 25px;height:25px;border-radius: 50%;margin-right: 5px" v-else src="https://sass-files.njqianyan.cn//saas/zoQ9He86SsdBWHdvObmm0890iuB7fa9q8rg9Ha68.webp">
          <div style="line-height: 18px;font-size: 12px;">{{ customer.name }}<br><span style="font-size: 12px;color: #aaaaaa">{{customer.level_name}}</span></div>
        </div>

        <!-- 客户预约区域 -->
        <div
          class="appointments-area"
          @mousedown="handleAreaClick(customer.id)"
        >
          <!-- 该客户的预约项 -->
          <div
            v-for="appointment in getCustomerAppointments(customer.id)"
            :key="appointment.id"
            class="appointment-box"
            :style="getAppointmentStyle(appointment)"
            @mousedown.stop="startDrag(appointment, $event)"
          >
            <div class="resize-handle top" @mousedown.stop="startResize(appointment, $event, 'top')"></div>
            <div class="appointment-content">
              <div class="appointment-title" :style="'background:'+appointment.color">
                <img :src="appointment.avatar" style="width: 20px;height: 20px;border-radius: 50%;border:1px solid #fff;"/>&nbsp;
                
              </div>
              <div class="appointment-time">
                {{appointment.username}}<br>
<!--                {{ formatTime(appointment.start) }}<br>-->
<!--                 {{ appointment.title }}<br>-->
<!--                预计:{{ appointment.end - appointment.start  }}min-->
              </div>
            </div>
            <div class="resize-handle bottom" @mousedown.stop="startResize(appointment, $event, 'bottom')"></div>
            <button class="delete-btn" v-if="appointment.status===1" @click="show_detail(appointment)">已到店</button>
            <button class="delete-btn" v-else  @click="show_detail(appointment)">操作</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  </n-scrollbar>




  <n-drawer v-model:show="data.select_appoint.draw" width="80%">
        <Detail :info-data="data.select_appoint" @call-parent="on_ref"/>
  </n-drawer>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import {
  NAvatar,
  NButton,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSelect,
  NTabPane,
  NTabs,
  NTag,
  useMessage
} from 'naive-ui'
import api from "@/api";
import Detail from "./detail.vue";
const message = useMessage()
const props = defineProps({
  customers: {
    type: Array,
    required: true,
    default: () => []
  },
  appointments: {
    type: Array,
    required: true,
    default: () => []
  },
  app_type: {
    type: String,
    required: true,
    default: () => []
  },
  startHour: {
    type: Number,
    default: 8
  },
  endHour: {
    type: Number,
    default: 20
  },
  hourHeight: {
    type: Number,
    default: 60
  },
  columnWidth: {
    type: Number,
    default: 200
  }
});

const emit = defineEmits([
  'update:appointments',
  'add-appointment',
  'delete-appointment',
    'call-parent'
]);

// 计算小时刻度
const hours = computed(() => {
  return Array.from({ length: props.endHour - props.startHour + 1 }, (_, i) => props.startHour + i);
});

const data = reactive({
  start:0,
  longs:0,
  select_appoint:{
    draw:false
  }
});

function show_detail(item){

  data.select_appoint = item
  data.select_appoint.draw = true
}


function on_ref(){
  emit('call-parent')
}

// 获取指定客户的预约
const getCustomerAppointments = (Id) => {
  return props.appointments
    .filter(a => a[props.app_type].includes(Id))
    .sort((a, b) => a.start - b.start);
};

// 格式化小时显示
const formatHour = (hour) => {
  return `${hour}:00`;
};

// 格式化时间显示
const formatTime = (time) => {
  const hours = Math.floor(time / 60);
  const mins = time % 60;
  return `${hours}:${mins < 10 ? '0' + mins : mins}`;
};

// 获取预约框样式
const getAppointmentStyle = (appointment) => {
  const startOffset = (appointment.start - props.startHour * 60) * (props.hourHeight / 60);
  const duration = appointment.end - appointment.start;
  const height = duration * (props.hourHeight / 120);

  return {
    top: `${startOffset}px`,
    height: `${height}px`,
    backgroundColor:  '#eee'
    // backgroundColor: appointment.color || '#4CAF50'
  };
};

// 拖动相关状态
const dragging = ref(false);
const resizing = ref(false);
const currentAppointment = ref(null);
const startY = ref(0);
const startTimeValue = ref(0);
const resizeType = ref('');
const lastAppliedDelta = ref(0); // 记录最后应用的30分钟单位

// 开始拖动预约
const startDrag = (appointment, event) => {
  if(appointment.project_status_format!=='待确认'){
    return
  }
  dragging.value = true;
  currentAppointment.value = appointment;
  startY.value = event.clientY;
  startTimeValue.value = appointment.start;
  data.start = appointment.start;
  data.longs = appointment.longs;
  lastAppliedDelta.value = 0; // 重置最后应用的增量

  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('mouseup', stopDragMove);
};

// 处理拖动
const handleDrag = (event) => {
  if (!dragging.value) return;

  const dy = event.clientY - startY.value;
  const minutesPerPixel = 60 / props.hourHeight;
  const deltaMinutes = Math.round(dy * minutesPerPixel);
  
  // 计算30分钟单位的增量
  const deltaMinutes30 = Math.round(deltaMinutes / 30) * 30;
  
  // 只有当30分钟单位发生变化时才更新
  if (deltaMinutes30 !== lastAppliedDelta.value) {
    lastAppliedDelta.value = deltaMinutes30;
    
    const newStart = startTimeValue.value + deltaMinutes30;
    const duration = currentAppointment.value.end - currentAppointment.value.start;
    
    if(newStart >= 480 && newStart <= 1140) {
      // 更新预约时间
      const updatedAppointments = props.appointments.map(a => {
        if (a.id === currentAppointment.value.id) {
          data.start = newStart
          return {
            ...a,
            start: Math.max(0, newStart),
            end: Math.max(0, newStart + duration)
          };
        }
        return a;
      });

      emit('update:appointments', updatedAppointments);
    }
  }
};

// 停止拖动
const stopDragMove = () => {
  dragging.value = false;
  last_update()
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDragMove);
};

// 开始调整大小
const startResize = (appointment, event, type) => {
  if(appointment.project_status_format!=='待确认'){
    return
  }
  resizing.value = true;
  currentAppointment.value = appointment;
  startY.value = event.clientY;
  startTimeValue.value = type === 'top' ? appointment.start : appointment.end;
  resizeType.value = type;
  data.start = appointment.start;
  data.longs = appointment.longs;
  lastAppliedDelta.value = 0; // 重置最后应用的增量

  document.addEventListener('mousemove', handleResize);
  document.addEventListener('mouseup', stopResize);
};

// 处理调整大小
const handleResize = (event) => {
  if (!resizing.value) return;

  const dy = event.clientY - startY.value;
  const minutesPerPixel = 60 / props.hourHeight;
  const deltaMinutes = Math.round(dy * minutesPerPixel);
  
  // 计算30分钟单位的增量
  const deltaMinutes30 = Math.round(deltaMinutes / 30) * 30;
  
  // 只有当30分钟单位发生变化时才更新
  if (deltaMinutes30 !== lastAppliedDelta.value) {
    lastAppliedDelta.value = deltaMinutes30;

    const updatedAppointments = props.appointments.map(a => {
      if (a.id === currentAppointment.value.id) {
        if (resizeType.value === 'top') {
          const newStart = startTimeValue.value + deltaMinutes30;
          if (newStart < a.end) {
            data.start = newStart
            data.longs = a.end - newStart
            return { ...a, start: Math.max(0, newStart) };
          }
        } else {
          const newEnd = startTimeValue.value + deltaMinutes30;
          if (newEnd > a.start) {
            data.longs = newEnd - a.start
            return { ...a, end: newEnd };
          }
        }
      }
      return a;
    });

    emit('update:appointments', updatedAppointments);
  }
};

function last_update(){
  api.updateAppointment({
      id:currentAppointment.value.id,
      start:data.start,
      longs:data.longs,
    }).then((res) => {
       // message.success('预约更新完成')
    })

}



// 停止调整大小
const stopResize = () => {
  resizing.value = false;
  last_update()
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('mouseup', stopResize);
};

onUnmounted(() => {
  document.removeEventListener('mousemove', handleDrag);
  document.removeEventListener('mouseup', stopDragMove);
  document.removeEventListener('mousemove', handleResize);
  document.removeEventListener('mouseup', stopResize);
});

</script>

<style scoped>
.schedule-container {
  display: flex;
  height: 80vh;
  overflow: hidden;
  background: #fff;
  border-radius: 0;
}

.time-column {
  position: relative;
  width: 60px;
  height: 100%;
  flex-shrink: 0;
  margin-top: 60px;
  background: #f5f5f5;
}

.time-mark {
  position: absolute;
  left: 0;
  transform: translateY(-50%);
  padding: 5px;
  font-size: 14px;
  text-indent: 10px;
}

.customers-container {
  display: flex;
  flex-grow: 1;
  height: 100%;
  overflow-x: auto;
  overflow-y: hidden;
}
.time_big{
  background: #f5f5f5;
}

.customer-column {
  position: relative;
  height: 100%;
  border-left: 1px solid #eee;
  flex-shrink: 0;

}

.customer-header {
  height: 60px;
  padding: 10px;
  background: #f5f5f5;
}


.appointments-area {
  position: relative;
  height: calc(100% - 40px);
  cursor: pointer;
}

.appointment-box {
  position: absolute;
  left: 10px;
  right: 10px;
  border-radius: 6px;
  padding: 0px;
  color: white;
  cursor: move;
  user-select: none;
  box-sizing: border-box;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.appointment-content {
  /* height: calc(100% - 10px); */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  border-radius: 6px;
}

.appointment-title {
  font-size: 12px;
  margin-bottom: 3px;
  height: 30px;
  display: flex;
  align-items: center;
  padding: 0 5px;
}

.appointment-time {
  font-size: 12px;
  color: #655948;
  padding:0 5px;
  line-height: 15px;
}

.resize-handle {
  position: absolute;
  height: 6px;
  width: 100%;
  left: 0;
  cursor: ns-resize;
  z-index: 10;
}

.resize-handle.top {
  top: 0;
}

.resize-handle.bottom {
  bottom: 0;
}

.delete-btn {
  position: absolute;
  top: 6px;
  right: 4px;
  padding: 2px 6px;
  background: #fff;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 10px;
  color: #d95b74;
  border:0;
}


</style>